package com.idnx.mynewsdemo.presenter;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.idnx.mynewsdemo.entity.NewsBean;
import com.idnx.mynewsdemo.http.ApiServer;
import com.idnx.mynewsdemo.http.ApiServiceManager;

import java.util.ArrayList;
import java.util.List;


import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainViewModel extends ViewModel {
    private MutableLiveData<List<NewsBean.ResultBean.DataBean>> dataBeans;
    private final ApiServer apiService;
    public MainViewModel() {
        dataBeans = new MutableLiveData<>();
        apiService = ApiServiceManager.get().create(ApiServer.class, "https://v.juhe.cn/toutiao/");
    }
    public LiveData<List<NewsBean.ResultBean.DataBean>> getDataBeans() {
        return dataBeans;
    }

    public void fetchData() {
        Call<NewsBean> call = apiService.getGithubData("top", 1, 30, 0, "2472b8f4601b22ad132094c75edd42ef");
        call.enqueue(new Callback<NewsBean>() {
            @Override
            public void onResponse(Call<NewsBean> call, Response<NewsBean> response) {
                if (response.body() != null && response.body().getResult() != null) {
                    dataBeans.postValue(response.body().getResult().getData());
                } else {
                    dataBeans.postValue(new ArrayList<>());
                }
            }

            @Override
            public void onFailure(Call<NewsBean> call, Throwable t) {
                dataBeans.postValue(new ArrayList<>());
            }
        });
    }
}
